// components/searchTmp/searchTmp.js
import * as util from '../../utils/util';

Component({
  /**
   * 组件属性
   */
  properties: {
    placeholder: {
      type: String,
      value: ''
    },
    inputValue: {
      type: String,
      value: '',
      observer: function (newValue) {
        if (newValue) {
          this.setData({
            showClearIcon: true
          });
        } else {
          this.setData({
            showClearIcon: false
          });
        }
      }
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    showClearIcon: false
  },

  /**
   * 组件方法
   */
  methods: {
    bindSearchKey(e) {
      const eventDetail = e.detail.value;
      this.setData({
        inputValue: eventDetail
      });
      // 非全空格
      if (eventDetail && eventDetail.trim().length) {
        this.setData({
          showClearIcon: true
        });

        // 全空格
      } else if (eventDetail && eventDetail.length) {
        this.setData({
          showClearIcon: false
        });
        wx.showToast({
          icon: 'none',
          title: '请输入搜索关键字'
        });
        return
      }
      util.debounce(() => {
        this.triggerEvent('getKeyInput', this.data.inputValue.trim());
      }, 800)();
    },
    clearSearch(params) {
      this.setData({
        inputValue: ''
      })
      this.triggerEvent('handleClearSearch', '');
    },
    goToSearch(e) {
      const eventDetail = this.data.inputValue.trim();
      if (!eventDetail) {
        wx.showToast({
          icon: 'none',
          title: '请输入搜索关键字'
        });
        return;
      }
      this.triggerEvent('handleSearch', this.data.inputValue.trim());
    },
    confirm(e) {
      const eventDetail = e.detail.value;
      this.setData({
        inputValue: eventDetail
      });
      this.goToSearch(null);
    }
  }
})